// 根据传入的Code反向查询
export const getTreeNodePath = (tree = [], fieldValue, fieldName = 'id', childrenName = 'children') => {
    let treeData = tree;
    let result = [];

    if (!Array.isArray(tree)) {
        treeData = [tree];
    }

    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < treeData.length; i++) {
        if (treeData[i][fieldName] === fieldValue) {
            result.push(treeData[i]);
            break;
        }
        if (treeData[i][childrenName]?.length) {
            result = result.concat(getTreeNodePath(treeData[i][childrenName], fieldValue, fieldName, childrenName));
            if (result.length) {
                result.unshift(treeData[i]);
                break;
            }
        }
    }
    return result;
};

export const disableNodes = (tree = [], disabledMap = [], fieldName = 'id', childrenName = 'children') => {
    if (!disabledMap.length) {
        return tree;
    }
    return tree.map(node => {
        if (node[childrenName]?.length) {
            return {
                ...node,
                [childrenName]: disableNodes(node[childrenName], disabledMap, fieldName, childrenName),
                disabled: disabledMap.includes(node[fieldName])
            };
        }
        return {
            ...node,
            disabled: disabledMap.includes(node[fieldName])
        };
    });
};

export const arrayTransformToObj = (
    city = [],
    countryField = 'country',
    provinceField = 'province',
    cityField = 'city',
    regionField = 'region'
) => {
    if (city && Array.isArray(city)) {
        return {
            [countryField]: city[0] || '',
            [provinceField]: city[1] || '',
            [cityField]: city[2] || '',
            [regionField]: city[3] || ''
        };
    }
    return {
        [countryField]: '',
        [provinceField]: '',
        [cityField]: '',
        [regionField]: ''
    };
};

export const objTransformToArray = (
    city,
    countryField = 'country',
    provinceField = 'province',
    cityField = 'city',
    regionField = 'region'
) => [city[countryField], city[provinceField], city[cityField], city[regionField]].filter(Boolean);

export const autoTransformLocaleValue = (
    area = [],
    value = [],
    fieldName = 'nameZh',
    childrenName = 'children',
    transformFieldName = 'nameZh'
) => {
    let result = [];
    area.forEach(item => {
        if (value.includes(item[fieldName])) {
            result.push(item[transformFieldName]);
        }
        if (item[childrenName]?.length) {
            result = result.concat(
                autoTransformLocaleValue(item[childrenName], value, fieldName, childrenName, transformFieldName)
            );
        }
    });
    return result;
};

export const isChineseLanguage = value => {
    const regex = /^[\u4E00-\u9FA5].+$/g;
    return regex.test(value);
};
